/*
 * 消息首页
 * page消息
 */
import 'dart:convert';

import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/common/class/date/index.dart';
import 'package:qgchat/common/class/eventBus/index.dart';
import 'package:qgchat/common/class/sql/Sql.dart';
import 'package:qgchat/common/class/videoCall/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/LocalTalkRecordModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:qgchat/widgets/avatar.dart';
import 'package:qgchat/widgets/easyRefreshWidget.dart';
import 'package:qgchat/widgets/tipsDialog.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MsgIndex extends StatefulWidget {
  MsgIndex({Key key}) : super(key: key);

  @override
  _MsgIndexState createState() => _MsgIndexState();
}

class _MsgIndexState extends State<MsgIndex> {
  final ValueNotifier<bool> notifier = ValueNotifier<bool>(false);

  @override
  void initState() {
    super.initState();
    notifier.addListener(() {
      if (!mounted) return;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: true,
        brightness: Brightness.light,
        title: Text(
          "消息",
          style: TextStyle(
            color: Colors.black,
            fontSize: px(34),
            fontWeight: FontWeight.bold,
          ),
        ),
        // title: notifier.value
        //     ? Row(
        //         mainAxisAlignment: MainAxisAlignment.center,
        //         children: [
        //           CupertinoActivityIndicator(),
        //           SizedBox(width: px(20)),
        //           Text(
        //             '加载中...',
        //             style: TextStyle(
        //               color: Colors.black,
        //               fontSize: px(34),
        //               fontWeight: FontWeight.bold,
        //             ),
        //           ),
        //         ],
        //       )
        //     : Text(
        //         "消息",
        //         style: TextStyle(
        //           color: Colors.black,
        //           fontSize: px(34),
        //           fontWeight: FontWeight.bold,
        //         ),
        //       ),
      ),
      body: _BuildBody(notifier: notifier),
    );
  }
}

class _BuildBody extends StatefulWidget {
  final ValueNotifier<bool> notifier;
  _BuildBody({this.notifier, Key key}) : super(key: key);

  @override
  __BuildBodyState createState() => __BuildBodyState();
}

class __BuildBodyState extends State<_BuildBody> {
  GlobalKey<_ChatListState> childKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      header: EasyRefreshSetting.header,
      onRefresh: () async {
        childKey.currentState.refresh();
      },
      child: SingleChildScrollView(
        child: Column(
          children: [
            // 标签按钮
            _TabView(),
            // 生成间隔
            Container(
              width: w100(context),
              height: px(16),
              color: col("f5f7fa"),
            ),
            // 聊天列表
            Provide<UserState>(
              builder: (context, child, user) {
                if (user?.info?.memberToken == null) return Container();
                return ChatList(key: childKey, notifier: widget.notifier);
              },
            ),
          ],
        ),
      ),
    );
  }
}

/// 消息页tab导航按钮数据
class _Tab {
  _Tab(this.icon, this.title, this.count, this.navigator);

  final String icon;
  final String title;
  final int count;
  final String navigator;
}

class _TabView extends StatefulWidget {
  _TabView({Key key}) : super(key: key);

  @override
  __TabViewState createState() => __TabViewState();
}

class __TabViewState extends State<_TabView> {
  List<_Tab> tabs = [
    _Tab("assets/images/icon/msg1.png", "预约", 3, "/make"),
    _Tab("assets/images/icon/msg2.png", "通话", 65, "/call"),
    _Tab("assets/images/icon/msg3.png", "金币", 156, "/gold"),
  ];

  // 底部边框样式 最后一个元素没有边框
  BoxDecoration borderBottomStyle(i) {
    if (i == tabs.length - 1) {
      return null;
    } else {
      return BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: col("edeff2"),
            width: 1,
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return Container();
        String json = snapshot.data.getString('userinfo');
        if (json != null) {
          Map userInfo = deJson(json);
          if (userInfo['member_type'] == 1) {
            tabs = [
              _Tab("assets/images/icon/msg1.png", "预约", 3, "/make"),
              _Tab("assets/images/icon/msg2.png", "通话", 65, "/call"),
              _Tab("assets/images/icon/msg3.png", "金币", 156, "/gold"),
              _Tab("assets/images/icon/msg4.png", "评价", 51, "/assess")
            ];
          }
        }

        return Column(
          children: List.generate(
            tabs.length,
            (index) => Container(
              color: Colors.white,
              child: FlatButton(
                onPressed: () {
                  final user = Provide.value<UserState>(context);
                  final info = user.info;
                  final isLogin = info != null;
                  if (isLogin) {
                    goPage(context, tabs[index].navigator);
                  } else {
                    TipsDialog.login(
                      context,
                      () {
                        goPage(context, '/phoneLogin');
                      },
                    );
                  }
                },
                padding: EdgeInsets.only(right: px(30), left: px(11)),
                child: Row(
                  children: <Widget>[
                    // icon
                    Container(
                      padding: EdgeInsets.only(top: px(19)),
                      child: Image.asset(
                        tabs[index].icon,
                        width: px(126),
                        height: px(126),
                      ),
                    ),
                    // 内容
                    Expanded(
                      child: Container(
                        height: px(140),
                        decoration: borderBottomStyle(index),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Text(
                              tabs[index].title,
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(34),
                              ),
                            ),
                            Container(
                              child: Row(
                                children: <Widget>[
                                  // tipsCount(tabs[index].count),
                                  Container(
                                    margin: EdgeInsets.only(left: px(25)),
                                    child: Image.asset(
                                      "assets/images/icon/right.png",
                                      width: px(14),
                                      height: px(26),
                                    ),
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

class ChatList extends StatefulWidget {
  final ValueNotifier<bool> notifier;
  ChatList({this.notifier, Key key}) : super(key: key);

  @override
  _ChatListState createState() => _ChatListState();
}

class _ChatListState extends State<ChatList> with WidgetsBindingObserver {
  /// 消息列表
  List<LocalTalkRecordModel> list = [];

  /// 当前用户token
  String token;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    final not = Global.socketNot;
    if (not.value != null) {
      not.value
          .map((str) => jsonDecode(str))
          .where((cls) => cls['datatype'] == 'message')
          .map(
        (cls) {
          final info = Provide.value<UserState>(context).info;
          return LocalTalkRecordModel.fromJson({
            "text": cls['data']['msg'],
            "member_nickname": cls['data']['name'],
            "member_head": cls['data']['head'],
            "from_id": cls['data']['token'],
            "to_id": info.memberToken,
          });
        },
      ).listen(
        (res) {
          final i = list.indexWhere((item) {
            final b1 = [item.fromId, item.toId].contains(res.fromId);
            final b2 = [item.fromId, item.toId].contains(res.toId);
            final b3 = res.fromId != res.toId;
            return b1 && b2 && b3;
          });

          if (i == -1) return;

          list[i].text = res.text;
          list[i].createtime = res.createtime;
          list[i].read = 0;
          setState(() {});
        },
      );
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Future didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) refresh();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    refresh();
  }

  Future refresh() async {
    final info = Provide.value<UserState>(context).info;
    token = info.memberToken;

    // 同步线上数据
    widget.notifier.value = true;
    await Sql().synchronization(token);

    // 加载数据
    final value = await Sql().queryUserRecord(token);
    if (!mounted) return;
    list = value;
    setState(() {});
    bus.emit("changeReadStatus");
    widget.notifier.value = false;

    // Logger().i(list);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: List.generate(
        list.length,
        (i) {
          final info = list[i];
          final otherToken = [info.toId, info.fromId].firstWhere(
            (item) => item != token,
            orElse: () => null,
          );

          return GestureDetector(
            onTap: () {
              VideoCall.checkUserStatusAndGoChatPage(
                context,
                otherToken,
              ).then(
                (res) async {
                  await refresh();
                  await Sql().updateRead(token, otherToken);
                  await refresh();
                },
              );
            },
            child: Container(
              height: px(160),
              color: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: px(30)),
              child: Row(
                children: <Widget>[
                  Avatar(
                    '${info.memberHead}',
                    true,
                    token: otherToken,
                  ),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: px(38)),
                      padding: EdgeInsets.only(left: px(25)),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                            color: col("edeff2"),
                            width: 1,
                          ),
                        ),
                      ),
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  "${info.memberNickname}",
                                  style: TextStyle(
                                    height: .95,
                                    color: col("303133"),
                                    fontSize: px(34),
                                  ),
                                ),
                                Text(
                                  "${Date.simple(info.createtime, format: "m月d日 h:i")}",
                                  style: TextStyle(
                                    height: .95,
                                    color: col("bfc2cc"),
                                    fontSize: px(26),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: px(20)),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Container(
                                  width: px(435),
                                  child: Text(
                                    "${info.text}",
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      height: .99,
                                      color: col("909399"),
                                      fontSize: px(26),
                                    ),
                                  ),
                                ),
                                Badge(showBadge: info.read == 0),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
